package uk.co.revisual.pivot.mediators
{
	import org.puremvc.as3.multicore.interfaces.INotification;
	import org.puremvc.as3.multicore.interfaces.IProxy;
	import org.puremvc.as3.multicore.patterns.mediator.Mediator;
	import org.puremvc.as3.multicore.utilities.statemachine.StateMachine;
	
	import uk.co.revisual.pivot.proxies.PivotProxy;
	import uk.co.revisual.pivot.vos.PivotVO;

	public class PivotMediator extends Mediator
	{
		private static const NAME:String = "PivotMediator";
		private var _model:IProxy;
		private var _currentState:String;
		
		public function PivotMediator(model:IProxy)
		{
			_model = model;
			super( NAME);
		}
		
		override public function listNotificationInterests():Array{
			var interests:Array = [ StateMachine.CHANGED ]
			return PivotProxy(_model).getInterests().concat(interests);
		}
		
		override public function handleNotification(note:INotification):void{
			switch(note.getName()){
				case StateMachine.CHANGED:
					_currentState = note.getType();
					break;
				default:
					pivot( note );
			}

		}
		
		private function pivot( note:INotification ):void{
			var redirectList:Array = PivotProxy(_model).getPivotList( note.getName(), _currentState ),
				vo:PivotVO;
			for each (vo in redirectList){
				if( !vo.state || vo.state == _currentState )
					sendNotification( vo.address, note.getBody(), vo.type || note.getType() );				
			}
		}
		
	}
}